import { Platform } from "react-native";
// import AsyncStorage from "@react-native-community/async-storage";
import config from "config";
// import DeviceInfo from "react-native-device-info";
import { Toast } from "@ant-design/react-native";
import RNFetchBlob from "react-native-fetch-blob";

import _app from "../app";
import { getStore, setStore, getQuery } from "./index";

const codeMessage = {
  200: "服务器成功返回请求的数据。",
  201: "新建或修改数据成功。",
  202: "一个请求已经进入后台排队（异步任务）。",
  204: "删除数据成功。",
  400: "发出的请求有错误，服务器没有进行新建或修改数据的操作。",
  401: "用户没有权限（令牌、用户名、密码错误）。",
  403: "用户得到授权，但是访问是被禁止的。",
  404: "发出的请求针对的是不存在的记录，服务器没有进行操作。",
  406: "请求的格式不可得。",
  410: "请求的资源被永久删除，且不会再得到的。",
  422: "当创建一个对象时，发生一个验证错误。",
  500: "服务器发生错误，请检查服务器。",
  502: "网关错误。",
  503: "服务不可用，服务器暂时过载或维护。",
  504: "网关超时。",
};

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const errortext = codeMessage[response.status] || response.statusText;
  const error = new Error(response.statusText);
  error.errCode = response.errCode;
  error.errortext = errortext;
  throw error;
}

// 业务成功检查
const checkCode = async data => {
  // 登录的权限失效
  if (data !== undefined) {
    if (data.errCode === -2) {
      // 清除用户信息，跳转到登录页
      // Toast.info("登录已过期！", 1);
      // console.log("鉴权失败"); // eslint-disable-line
      // const currentScreen = getActiveRouteName(_app.getApp()._store.state);
      // AsyncStorage.multiRemove(["token"]); // 清空token
      await setStore("token", "");
      _app.getApp()._store.dispatch({
        type: "public/checklogin",
        payload: { isLogin: false },
      });
      return data;
    } else if (data.errCode === 0) {
      // 正常的请求返回
      return data;
    }
  }

  // 错误的返回处理
  const errortext = data.errMsg || "后端接口返回异常";
  const error = new Error(data.errCode || 444);
  error.errCode = data.errCode || 444;
  error.errortext = errortext;
  throw error;
};

export const _fetch = async (url, params, option = {}) => {
  const token = (await getStore("token")) || "none";
  if (token === null || token === undefined || token === "none") {
    _app.getApp()._store.dispatch({
      type: "public/checklogin",
      payload: { isLogin: false },
    });
  } else {
    _app.getApp()._store.dispatch({
      type: "public/checklogin",
      payload: { isLogin: true },
    });
  }

  // const uuid = (await getStore("uuid")) || "none";
  const headers = {
    "Content-Type": "application/json",
    // Authorization: token,
    // app_token: "eyJhbGciOiJSUzI1NiJ9.eyJyb2xlIjpbImhxdF9hZG1pbiJdLCJzdWIiOiJnYXRld2F5X2FkbWluIiwiZXhwIjoxNTcyMDg0NTQyfQ.TwPi4YaLp7GBcvwQTYegyt0qhUiYigZLLnIttaFlsgS9bvbiTWwvE63Z4dQ6MUA4gXuR4y1HkQOfEikIosp4ENndNQRn4xuTesXzlR5W1E17gFpKCyfxunVKpLaEi3pCe6iGumw-V493ZES7qig2cw8_tdVJkku2MCkDmQClJv2sCrStVcP-MU4N47jLqXLxmc-IdgSiTsV_YDwtWxGCblLcKzsmsbb92EMu02WpjhZs8fcH7FxjX6q_GfFzdqd1xJDEnUgV9-34g1eAxgAuaI4dflmLpjJSVjD4Mdk4nOURr948mYnKhRXkExdFQz8LjfR_qnKIybAbsAfGywwySQ",
    app_token: token,
    DEVICETYPE: Platform.OS === "ios" ? "IOS" : "Android",
    DEVICEID: "debug_001", // DeviceInfo.getUniqueId(),
    ...(option.header || {}),
  };

  const _timeOut = () => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const error = new Error("请求超时");
        error.errCode = 504;
        error.errortext = "请求超时";
        reject(error);
      }, 60 * 1000);
    });
  };

  return Promise.race([
    fetch(url, {
      credentials: "include",
      ...params,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        ...headers,
      },
    }),
    _timeOut(),
  ])
    .then(checkStatus)
    .then(response => response.json())
    .then(checkCode)
    .catch(err => {
      // const { errortext } = err;

      // Toast.fail(errortext, 2);
      return { ...err, message: JSON.stringify({ url, params }) };
    });
};

export const get = (url, query, headers) => {
  const {
    server: { target = "" },
  } = config;
  const url2 = query ? `${target}${url}?${getQuery(query)}` : `${target}${url}`;
  return _fetch(
    url2,
    {
      method: "GET",
    },
    {
      ...headers,
      // verifyCode: "17c024f9-719b-4121-91ef-9a0d38dab71b",
    }
  );
};

export const post = (url, body, headers) => {
  const {
    server: { target = "" },
  } = config;
  return _fetch(
    `${target}${url}`,
    {
      method: "POST",
      body: JSON.stringify(body),
    },
    {
      ...headers,
      // verifyCode: "17c024f9-719b-4121-91ef-9a0d38dab71b",
    }
  );
};

// // **************文件上传**************
export const uploadImage = async (url, response) => {
  const token = (await getStore("token")) || "none";
  if (token === null || token === undefined || token === "none") {
    _app.getApp()._store.dispatch({
      type: "public/checklogin",
      payload: { isLogin: true },
    });
  } else {
    _app.getApp()._store.dispatch({
      type: "public/checklogin",
      payload: { isLogin: true },
    });
  }
  const {
    server: { target = "" },
  } = config;

  console.log("response:", response);
  const result = await RNFetchBlob.fetch(
    "POST",
    `${target}${url}`,
    {
      app_token: token,
      DEVICETYPE: Platform.OS === "ios" ? "IOS" : "Android",
      DEVICEID: DeviceInfo.getUniqueId(),
      "Content-Type": "multipart/form-data",
    },
    [
      {
        name: "file",
        filename: response.fileName,
        type: response.type,
        data: RNFetchBlob.wrap(response.uri),
      },
      // elements without property `filename` will be sent as plain text
    ]
  )
    .then(res => {
      const result2 = JSON.parse(res.data);
      // return res.data.json();
      return result2;
    })
    .catch(err => {
      const { errMsg = "请求异常" } = err;
      Toast.fail(errMsg, 2);
      return { ...err, message: JSON.stringify({ url, response }) };
    });

  return result;
};
